import React, { useEffect } from 'react';
import { Navigate, useLocation, useNavigate } from "react-router-dom";
import { observer } from "mobx-react-lite";
import user from "@/store/user";
import Loading from "@/components/Loading"

/**
 * 这里判断要访问的页面是否在用户权限数组中，
 * 1. 用户权限的页面url中，有 /:id 这样的，但是页面访问的url中id是指定的某个值，所以需要进行单独处理
 * 2. 如果是普通的url，则直接进行相等判断
 */
function authJudge(permissions, path) {
    for(let i = 0; i < permissions.length; i++) {
        let per = permissions[i];
        if(per.indexOf(':') > -1) {
            let _url = per.split(':')[0];
            if(path.indexOf(_url) > -1) {
                return true;
            }
        } else if(per === path) {
            return true;
        }
    }
    return false;
}

const AuthPage = observer(({ children }) => {
    const location = useLocation()
    const navigate = useNavigate()
    const { pathname } = location;

    useEffect(() => {
        if (!user.token || user.isError) {
            navigate('/login', { replace: true })
        } else {
            let perLength = user.permissions.length;

            if (perLength === 0) {
                user.initAuthList()
            } else if (!authJudge(user.permissions, pathname)) {
                navigate('/403', { replace: true })
            }
        }
    }, [pathname])

    return (
        authJudge(user.permissions, pathname) ? (<>{ children }</>) : (
            <Loading />
        )
    )
})

export default AuthPage;